from alipay import AliPay
from django.conf import settings
from django.shortcuts import render
from django.views import View

from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from orders.models import OrderInfo
from django import http
import os
from payment.models import Payment


# Create your views here.
class PaymentStatusView(View):
    def get(self,request):
        # 获取前端传入的请求：以下为支付宝的回调请求
        # http://www.meiduo.site:8000/payment/status/?
        # charset=utf-8
        # out_trade_no=20191011113344000000001
        # method=alipay.trade.page.pay.return
        # total_amount=17897.00
        # sign=cszi9p1lRs1nECs35xP3gJuDK6RUzFmeVExM1FR5TbYVn18dcyqYJVtu4S3jHOppG%2BQuDZ1xwdamvC1oNxWSqBC354AfX%2F1dDDIA7quxUSe2LxY1o8380b2ZXiF6shXwXceCyqeXhu3qLJTrDpB%2FsvCX2CbkEo%2FGL5mO2wAc7dbgxz%2Fe8ICHFzonNBdaja6g0eq%2Bu%2FH%2FEwufKO8u9%2FvjgIuz6HGXxO44UZWRLHvv4vf1v%2FtoUYGx23CvwTwFkj0%2F1PuIYybsfYPrk%2FEpTqWoYEeipCdNFp5j1mgyBWY0NqRPbe60Yl0oI0iPfR%2BWRDyxYPya2DQNo2OyQHfncqySbQ%3D%3D
        # trade_no=2019101122001484391000037776
        # auth_app_id=2016101300675217
        # version=1.0
        # app_id=2016101300675217
        # sign_type=RSA2
        # seller_id=2088102179358974
        # timestamp=2019-10-11+19%3A37%3A04
        query_dict=request.GET
        data=query_dict.dict()
        #获取请求中的signature并删除请求中的signature
        signature = data.pop('sign')
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 利用alipay自带方法校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, signature)
        if success:
            # 读取orderid
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
            # 响应trade_id
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return http.HttpResponseForbidden('非法请求')



class PaymentView(LoginRequiredJSONMixin, View):
    def get(self, request, order_id):
        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception:
            return http.HttpResponseForbidden('订单信息错误')
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})